﻿#region MIT License
/*

Copyright (C) 2011 by Timothy A. Barela

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/
#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;

namespace Sharpener.Analysis
{
	public class BasicBlock
	{
		public Instruction Head { get; private set; }
		public Instruction Tail { get; private set; }

		public List<BasicBlock> Predecessors { get; private set; }
		public List<BasicBlock> Successors { get; private set; }

		private BasicBlock()
		{
			Predecessors = new List<BasicBlock>();
			Successors = new List<BasicBlock>();
		}

		public BasicBlock( Instruction head, Instruction tail )
			: this()
		{
			Head = head;
			Tail = tail;
		}

		public static List<BasicBlock> ScanForBlocks( IList<Instruction> instructions )
		{
			var leaders = scanForBlockLeaders(instructions);
			List<BasicBlock> results = new List<BasicBlock>(leaders.Length);

			for( int i=0;i<leaders.Length;i++)
			{
				var block = new BasicBlock();

				block.Head = instructions[leaders[i]];

				if(i < leaders.Length - 1)
					block.Tail = instructions[leaders[i+1] - 1];
				else
					block.Tail = instructions[instructions.Count - 1];

				results.Add(block);
			}

			return results;
		}

		internal static int[] scanForBlockLeaders( IList<Instruction> instructions )
		{
			var leaderSet = new Dictionary<int, int>();
			int[] result = null;
			int index = 0;

			leaderSet.Add(0,0);

			foreach( var inst in instructions )
			{
				switch(inst.OpCode.FlowControl)
				{
					case FlowControl.Branch:
					case FlowControl.Cond_Branch:
						//add the instruction that follows this branch as a leader
						if(index < instructions.Count - 1)
						{
							if(!leaderSet.ContainsKey(index + 1))
								leaderSet[index+1] = 0;
						}

						var targetIndex = instructions.IndexOf(inst.Operand as Instruction);

						//didnt find the instruction, error
						if(targetIndex == -1)
							throw new Exception("Something went wrong while scanning for BasicBlockBoundaries.");

						if( !leaderSet.ContainsKey(targetIndex) )
							leaderSet[targetIndex]=0;
						break;
				}

				index++;
			}

			result = new int[leaderSet.Keys.Count];
			leaderSet.Keys.CopyTo(result, 0);
			Array.Sort(result);

			return result;
		}

		public override string ToString()
		{
			return string.Format("BasicBlock: {0} --> {1}", Head, Tail);
		}
	}
}